package org.sfx.control

import org.sfx.rich.Enrich._
import javafx.scene.control.Label
import javafx.scene.layout.StackPane
import javafx.scene.control.ContextMenu
import javafx.scene.control.MenuItem
import javafx.scene.control.RadioMenuItem
import javafx.geometry.Side
import javafx.geometry.HPos
import javafx.geometry.VPos
import javafx.scene.control.Menu
import javafx.scene.input.MouseButton

class TabHandle(val tab: Tab) extends StackPane {
  val label = new Label(tab.text)
  this.getStyleClass().add("s4jfx-tab-handle")
  this.getChildren.add(label)
  
  this.tab.selectedProperty.addChangeListener { (observable, oldValue, newValue) =>
    TabHandle.this.impl_pseudoClassStateChanged("selected")
  }
  
  this.onMouseClicked { event =>
    if (!event.isAltDown && !event.isControlDown && !event.isShiftDown && !event.isMetaDown) {
      event.getButton match {
        case MouseButton.PRIMARY => {
          tab.tabPane.selectionModel.get().select(tab)
          event.consume()
        }
        case MouseButton.SECONDARY => {
          val contextMenu = new ContextMenu() {
            val menuClose = new MenuItem("Close") {
              this.onAction { event => tab.tabPane.tabs.remove(tab) }
            }
            val menuCloseOthers = new MenuItem("Close Others")
            val menuCloseAll = new MenuItem("Close All")
            this.getItems().addAll(menuClose, menuCloseOthers, menuCloseAll)
          }
          
          contextMenu.show(TabHandle.this, event.getScreenX, event.getScreenY)
          event.consume()
        }
      }

    }
  }
  
  override def impl_getPseudoClassState(): Long = {
    var l = super.impl_getPseudoClassState()
 
    if (this.tab.selected) {
      l |= PseudoClasses.selected
    }
 
    return l
  }
}
